import smtplib
import email.mime.multipart
import email.mime.text
from email.mime.application import MIMEApplication
from datetime import date, timedelta, datetime

import pymongo


def send_email(smtp_host, port, sendAddr, password, recipientAddrs, subject='', content=''):
    yesterday = date.today() - timedelta(1)
    yesterday = yesterday.strftime('%Y%m%d')
    msg = email.mime.multipart.MIMEMultipart()
    msg['from'] = sendAddr
    # 多个收件人的邮箱应该放在字符串中,用字符分隔, 然后用split()分开,不能放在列表中, 因为要使用encode属性
    msg['to'] = recipientAddrs
    msg['subject'] = subject
    content = content
    txt = email.mime.text.MIMEText(content, 'plain', 'utf-8')
    msg.attach(txt)
    print("准备添加附件...")
    # 添加附件，从本地路径读取。如果添加多个附件，可以定义part_2,part_3等，然后使用part_2.add_header()和msg.attach(part_2)即可。
    unicoms = coll_127.find({"orderstate": "0", "tel_type": "unicom", "orderdate": yesterday, "merchantid": "M2018081416281534235296"})
    part = MIMEApplication("\n".join(("充值|%s|%s|%s|%s" % (datetime.fromtimestamp(i['time']), i['ordernumber'], i['tel_number'], i['amount']) for i in unicoms)).encode())
    part.add_header('Content-Disposition', 'attachment', filename=("utf-8","", "联通%s.txt" % yesterday))  # 给附件重命名,一般和原文件名一样,改错了可能无法打开.
    msg.attach(part)
    # part_2
    cmccs = coll_127.find({"orderstate": "0", "tel_type": "cmcc", "orderdate": yesterday, "merchantid": "M2018081416281534235296"})
    part_2 = MIMEApplication("\n".join(("充值|%s|%s|%s|%s" % (datetime.fromtimestamp(i['time']), i['ordernumber'], i['tel_number'], i['amount']) for i in cmccs)).encode())
    part_2.add_header('Content-Disposition', 'attachment', filename=("utf-8","", "移动%s.txt" % yesterday))  # 给附件重命名,一般和原文件名一样,改错了可能无法打开.
    msg.attach(part_2)
    ctccs = coll_127.find({"orderstate": "0", "tel_type": "ctcc", "orderdate": yesterday, "merchantid": "M2018081416281534235296"})
    part_3 = MIMEApplication("\n".join(("充值|%s|%s|%s|%s" % (datetime.fromtimestamp(i['time']), i['ordernumber'], i['tel_number'], i['amount']) for i in ctccs)).encode())
    part_3.add_header('Content-Disposition', 'attachment', filename=("utf-8","", "电信%s.txt" % yesterday))  # 给附件重命名,一般和原文件名一样,改错了可能无法打开.
    msg.attach(part_3)
    smtp = smtplib.SMTP_SSL(smtp_host, port)  # 需要一个安全的连接，用SSL的方式去登录得用SMTP_SSL，之前用的是SMTP（）.端口号465或587
    smtp.login(sendAddr, password)  # 发送方的邮箱，和授权码（不是邮箱登录密码）
    smtp.sendmail(sendAddr, recipientAddrs.split(";"), str(msg))  # 注意, 这里的收件方可以是多个邮箱,用";"分开, 也可以用其他符号
    print("发送成功！")
    smtp.quit()


if __name__ == "__main__":
    try:
        client_127 = pymongo.MongoClient('mongodb://cs_user:cmcc5188@localhost:12018/cs_recharge')
        db_127 = client_127.cs_recharge
        coll_127 = db_127.rechange
        # 设置好邮箱信息
        smtpHost = 'smtp.139.com'  # 这是QQ邮箱服务器。如果是腾讯企业邮箱，其服务器为smtp.exmail.qq.com。其他邮箱需要查询服务器地址和端口号。
        port = 465  # 端口号
        sendAddr = '13418071372@139.com'  # 发送方地址
        # password = input("请输入邮箱授权码：")  # 手动输入授权码更安全.授权码的获取:打开qq邮箱->设置->账户->开启IMAP/SMTP服务->发送短信->授权码
        password = 'ycyz007'
        recipientAddrs = '3288235413@qq.com'  # 接收方可以是多个账户, 用分号分开,send_email()函数中手动设置
        subject = '每日报表'  # 主题
        content = '交易流水'  # 正文内容
        send_email(smtpHost, port, sendAddr, password, recipientAddrs, subject, content)  # 调用函数
    except Exception as err:
        print(err)
